<?php
namespace app\service;

use think\Log;

class VolcengineService
{
    /**
     * API密钥
     * @var string
     */
    private $_api_key;
    private $_timeout = 30;
    private $_model = 'doubao-seed-1.6-250615';
    private $_api_url = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions';
    
    
    /**
     * 构造函数
     */
    public function __construct($api_key,$model,$timeout= 30)
    {
        // 从配置中获取API密钥
        $this->_api_key = $api_key;
        $this->_model = $model;
        $this->_timeout = $timeout;
        if (empty($this->_api_key)) {
            throw new \Exception('api_key不能为空');  
        }
    }
    


    
    public function call($parameters)
    { 
        if (empty($parameters)) {
            throw new \Exception('parameters不能为空');
        }
        
        // 构建请求数据
        $requestData = [
            'model' => $this->_model,
            'messages' => [$parameters],
            'thinking' => [
                'type' => 'disabled',
            ],
        ];
        
       
        // 设置请求头
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->_api_key
        ];
        
        // 将数据转换为JSON字符串
        $jsonData = json_encode($requestData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        
        // debug_dump($requestData,$headers);
        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // 直接发送JSON字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 添加SSL选项
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        // 添加错误检查
        if ($curlError) {
            Log::error('CURL Error: ' . $curlError);
            throw new \Exception('CURL Error: ' . $curlError);
        }
        
        // debug_dump($response,$httpCode,$jsonData);
        
        // 检查响应状态
        if ($httpCode !== 200) {
            Log::error('API HTTP Error: ' . $httpCode . ', Response: ' . $response);
            throw new \Exception('API failed: http code: ' . $httpCode);
        }
        
        // 解析响应数据
        $responseData = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            Log::error('JSON Parse Error: ' . json_last_error_msg() . ', Response: ' . $response);
            throw new \Exception('Invalid JSON response');
        }
        
        // 火山引擎Chat Completions API标准响应格式
        if (!isset($responseData['choices']) || !isset($responseData['choices'][0])) {
            Log::error('Invalid response format: ' . $response);
            throw new \Exception('Invalid response format');
        }
        
        $content = $responseData['choices'][0]['message']['content'] ?? '';
        
        // 尝试解析为JSON（如果content是JSON格式的歌词数据）
        $result = json_decode($content, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $result;
        }
        
        // 如果不是JSON格式，直接返回文本内容
        return $content;
    }
} 